const COMMANDS = {
  ON: 'F1F10204000B0101137E', // 开机
  OFF: 'F1F10204000B0100127E', // 关机
  UVC: 'F1F10204000601010E7E', // UVC重置
  FILTER_TIMER: 'F1F1020400080101107E' // 滤网计时重置
}

/**
 * @decription 风速档位, 自动模式 夜间模式, 定时下发命令
 * @param {string} data
 * @param {number} type - 0,1,2  ['wind' | 'model' | 'timer']
 * @param {string} dataKey - 0001 | 0009 | 000a
 * @param {number} dataByte - 字节，默认为1byte
 * @example - 'F1F1 02 04 0001 0101 09 7E', // 风速(1挡)
 * @example - 'F1F1 02 05 000a 020078 22 7E', // 定时 120min
 */
const hexTransform = function(data, type, dataByte=1) {
  // const command = 'F1F1 0204 0001 01xx xx7E'

  const types = ['0001', '0009', '000a']
  const dataHex = numByByte(data, dataByte)

  console.log(dataHex, 'dataHex')
  console.log(dataHex.length, 'dataHex len')

  const startCode = 'F1F1'
  const feature = '02'
  const endCode = '7E'
  const dataKey = types[type]
  const dataLength = dataByte === 1 ? '04' : '05'

  let dataValue = `0${dataByte}${dataHex}`

  console.log(dataKey, 'dataKey--')
  console.log(dataLength, 'dataLength--')
  console.log(dataValue, 'dataValue--')


  const sumVerify = ml_getCheckCode(feature + dataLength + dataKey + dataValue)

  console.log(sumVerify, 'sumVerify')
  const hex = `${startCode}${feature}${dataLength}${dataKey}${dataValue}${sumVerify}${endCode}`
  console.log(hex)
  return hex
}

/**
 * @param {string} fullData 获取校验和值
 */
function ml_getCheckCode(fullData) {
  // fullData = fullData.toUpperCase().replace(/ /g, "");
  console.log(fullData, 'fullData')
	let intData = 0
	for (let i = 0; i < fullData.length; i++) {
		const _d = fullData.substr(i, 2)
		intData += parseInt(_d, 16) // parseInt(string, radix) string: 要被解析的值 radix: 进制数
		i++
	}

  console.log(intData, 'intData')
	console.log(intData&0xff, 'intData off')
	console.log(1111&0xff, 'intData off')
	console.log((1111&0xff).toString(16), 'intData off')

	let hexCheckCode = (intData&0xff).toString(16) // 255&0xff，取低位操作
	if (hexCheckCode.length == 1) {
		hexCheckCode = `0${hexCheckCode}`
	}
  console.log(hexCheckCode, 'hexCheckCode--')
	hexCheckCode = hexCheckCode.substr(hexCheckCode.length - 2, hexCheckCode.length)
  console.log(hexCheckCode, 'hexCheckCode')
	return hexCheckCode
}

function numByByte(data, dataByte) {
  let dataHex = parseInt(data).toString(16)
  console.log(dataHex, 'dataHex numByByte')

  if(dataByte==1) {
    dataHex = dataHex.padStart(2, '0') // 用0补位
  } else if(dataByte==2) {
    dataHex = dataHex.padStart(4, '0')
  }
  console.log(dataHex, 'dataHex numByByte las')
  return dataHex
}

/**
 * 夜间开，自动开 0011 3 => 03(hex)
 * 夜间开，自动关 0001 1 => 01(hex)
 * 夜间关，自动开 0010 2 => 02(hex)
 * 夜间关，自动关 0000 0 => 00(hex)
 */
const hexModel = (model) => {
  console.log(model, 'model-----')
  console.log(model.length, 'model length-----')
  if (model[0] == '' &&  model[1] == '') {
    return hexTransform('0', 1)
  } else if(model[0] == 'auto' &&  model[1] == 'night') {
    return hexTransform('03', 1)
  } else if(model[0] == '' &&  model[1] == 'night') {
    return hexTransform('01', 1)
  } else if(model[0] == 'auto' &&  model[1] == '') {
    return hexTransform('02', 1)
  }
}


const echartLevel = value => {
  if (value == 0) {
    return {
      level: 0,
      title: '优',
      v: 25
    }
  } else if (value == 1) {
    return {
      level: 1,
      title: '良',
      v: 50
    }
  } else if (value == 2) {
    return {
      level: 2,
      title: '差',
      v: 75
    }
  } else {
    return {
      level: 2,
      title: '差',
      v: 100
    }
  }
  
}

var ml_resp_fullUserBinaryData = "";
var ml_resp_start = "F2F2",
	ml_resp_end = "7E",
	ml_resp_code_length = 2,
	ml_resp_data_length = 2,
	ml_resp_check_code_length = 2;
var ml_req_start = "F1F1",
	ml_req_end = "7E";

const ml_parseOneFrameArray = _userBinaryData => {
  console.log(_userBinaryData, '_userBinaryData')
  
	_userBinaryData = _userBinaryData.toUpperCase()

  console.log(_userBinaryData, '_userBinaryData----')

	ml_resp_fullUserBinaryData += _userBinaryData

	console.log("_userBinaryData=" + _userBinaryData + ",ml_resp_fullUserBinaryData=" + ml_resp_fullUserBinaryData);

	var uartDataJsonArray = ""
	var dataRight = true

	while (ml_resp_fullUserBinaryData != "" && ml_resp_fullUserBinaryData.length > 0 && dataRight) {
		var start = ml_resp_fullUserBinaryData.indexOf(ml_resp_start)
    console.log(start, '=start')

		if (start == -1) {
      console.log('start == -1')
			ml_resp_fullUserBinaryData = "";
			uartDataJsonArray = "[" + uartDataJsonArray + "{}]";
			return JSON.parse(uartDataJsonArray);
		}

		var end = ml_resp_fullUserBinaryData.indexOf(ml_resp_end);
    console.log(end, '=end')

		if (end == -1) {
      console.log('end == -1')
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(start, ml_resp_fullUserBinaryData.length);
			dataRight = false;
			uartDataJsonArray = "[" + uartDataJsonArray + "{}]";
			return JSON.parse(uartDataJsonArray);
		}

		ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(start, ml_resp_fullUserBinaryData.length);
    console.log(ml_resp_fullUserBinaryData, '=ml_resp_fullUserBinaryData 11111')

		var _dataCode, _dataLength, _dataPayload, _dataCheckCode;

		var byParseUartData = ml_resp_fullUserBinaryData.substr(ml_resp_start.length, ml_resp_fullUserBinaryData.length);
    console.log(byParseUartData, '=byParseUartData 11111')

		if (byParseUartData.length < ml_resp_code_length) {
      console.log(11111)
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(end, ml_resp_fullUserBinaryData.length);
			continue;
		}

		_dataCode = byParseUartData.substr(0, ml_resp_code_length);
    console.log(_dataCode, '_dataCode 2222')
		byParseUartData = byParseUartData.substr(ml_resp_code_length, byParseUartData.length);
    console.log(byParseUartData, 'byParseUartData--2222')

		if (byParseUartData.length < ml_resp_data_length) {
      console.log(2222)
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(end, ml_resp_fullUserBinaryData.length);
			break;
		}
		_dataLength = byParseUartData.substr(0, ml_resp_data_length);
    console.log(_dataLength, '_dataLength 3333')
		byParseUartData = byParseUartData.substr(ml_resp_data_length, byParseUartData.length)
    console.log(byParseUartData, 'byParseUartData 3333')

		if (byParseUartData.length < (2 * parseInt(_dataLength, 16))) {
      console.log(3333)
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(end, ml_resp_fullUserBinaryData.length);
			break;
		}
		_dataPayload = byParseUartData.substring(0, (2 * parseInt(_dataLength, 16)))
    console.log(_dataPayload, '_dataPayload 4444')
		byParseUartData = byParseUartData.substr((2 * parseInt(_dataLength, 16)), byParseUartData.length)
    console.log(byParseUartData, 'byParseUartData 4444')

		if (byParseUartData.length < ml_resp_check_code_length) {
      console.log(4444)
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(end, ml_resp_fullUserBinaryData.length);
			break;
		}
		_dataCheckCode = byParseUartData.substr(0, ml_resp_check_code_length);
    console.log(_dataCheckCode, '_dataCheckCode 55555')

		if (!(ml_getCheckCode((_dataCode + _dataLength + _dataPayload)) == parseInt(_dataCheckCode, 16))) {
      console.log(55555)
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(end, ml_resp_fullUserBinaryData.length);
      console.log(ml_resp_fullUserBinaryData, 'ml_resp_fullUserBinaryData')
			break;
		}
		byParseUartData = byParseUartData.substr(ml_resp_check_code_length, byParseUartData.length);
    console.log(byParseUartData, 'byParseUartData 66666')

		if (byParseUartData.length < ml_resp_end.length) {
      console.log(66666)
			ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr(end, ml_resp_fullUserBinaryData.length);
			break;
		}
		ml_resp_fullUserBinaryData = ml_resp_fullUserBinaryData.substr((ml_resp_start + _dataCode + _dataLength + _dataPayload + _dataCheckCode + end).length, ml_resp_fullUserBinaryData.length);

    console.log(ml_resp_fullUserBinaryData, '==ml_resp_fullUserBinaryData')
		uartDataJsonArray += '{\"start\":\"' + ml_resp_start + '\",\"code\":\"' + _dataCode + '\",\"length\":\"' + _dataLength + '\",\"playload\":\"' + _dataPayload + '\",\"checkCode\":\"' + _dataCheckCode + '\",\"end\":\"' + ml_resp_end + '\"},';
	}


	uartDataJsonArray = "[" + uartDataJsonArray + "{}]";
  console.log(JSON.parse(uartDataJsonArray), '啦啦啦--')
	return JSON.parse(uartDataJsonArray);
}

const startCode = 'F2F2'
const endCode = '7E'
const featureCodes = ['F0', 'F3', '02']
const byteNum = 2
let receiverData = {
  '0001': '',
  '0002': '',
  '0003': '',
  '0004': '',
  '0005': '',
  '0007': '',
  '0009': '',
  '000A': '',
  '000B': '',
}
let dataNum = ''

const parseArray = binaryData => {
  console.log(binaryData, 'binaryData')
  const sumV = ml_getCheckCode(binaryData.substr(4, binaryData.length - 8))
  const sumB = binaryData.substr(binaryData.length - 4, 2)
  console.log('巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸', sumV)
  console.log('巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸', sumB)
  // alert('哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈', sumV)

  if (sumV.toUpperCase() != sumB.toUpperCase()) {
    return {
      verify: false,
      msg: '校验和不对'
    }
  }

  const featureD = featureData(binaryData.substr(8, binaryData.length - 12))
  const featureB = binaryData.substr(6, 2)

  console.log(featureD, 'featureD巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸')
  console.log(featureB, 'featureB巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸巴巴爸爸')

  if (featureD.toUpperCase() != featureB.toUpperCase()) {
    return {
      verify: false,
      msg: '数据长度不对'
    }
  }

  binaryData = binaryData.toUpperCase()
  // 去掉起始码(2byte) 功能码 数据长度 校验码  结束码
  let fullData = binaryData.substr(8, binaryData.length - 12) // 去掉起始码 结束码
  console.log(fullData, '去掉起始码 功能码 数据长度 校验码  结束码')
  // 得到功能码
  let featureCode = binaryData.substr(4, 2)
  console.log(featureCode, 'featureCode功能码')


  if (featureCodes.includes(featureCode)) {
    // 数据长度最小为4个字节
    dataNum = binaryData.substr(6, 2)
    console.log(dataNum,'77')
    
    // 数据的总字节数
    dataNum = parseInt(Number(`0x${dataNum}`), 10) * 2 

    console.log(dataNum, 'dataNum---')

    let current = 0

    if (dataNum >= 4) {

      while(dataNum > current) {
        console.log(current, 'current 每次循环的current')
        // 解析第一位
        let first = fullData.substr(current, 4)
        console.log(first,'first')
        current = current + 4

        const modelLen = parseInt(Number(`0x${fullData.substr(current, 2)}`), 10)


        console.log(fullData.substr(current, 2), 'ppp') 


        console.log(modelLen, 'modelLen---')

        if (modelLen == 1) {
          current = current + 2
          console.log(current, 'current 1')
          console.log(fullData.substr(current, 2), 'fullData(current, 2)')
          receiverData[first] = fullData.substr(current, 2)
          current = current + 2
          console.log(receiverData, 'receiverData 1')
        } else {
          current = current + 2
          console.log(current, 'current 2')
          receiverData[first] = fullData.substr(current, 4)
          console.log(receiverData, 'receiverData 2')
          current = current + 4
        }
      }
      console.log(receiverData, 'receiverData')
      return {
        verify: true,
        msg: 'ok',
        data: receiverData
      }
      // return receiverData
      
    }
  } else {
    console.log(featureCode, '功能码不对')
  }
  console.log()


}

const featureData = binaryData => {
  const timer = binaryData.length
  let arr = []
  for(let i=0; i<timer; i=i+2 ){
    arr.push(binaryData.substr(i, 2))
  }
  console.log(arr.length, 'arr.length')

  console.log(arr.length.toString().padStart(2, '0'), 'arr.length')
  

  let d = arr.length.toString().padStart(2, '0') // '04' 10进制
  console.log(d, 11)
  d = Number(d).toString(16) // 16进制 string
  console.log(d, 22)
  d = d.padStart(2, '0')
  console.log(d, 33)

  // d = parseInt(Number(`0x${d}`), 16)

  console.log(d, '哇哈哈哈哈哈 ------')
  // d = d.toString().padStart(2, '0')
  return d
}

const filterWind = step => {
  let data = {
    1: '60', 
    2: '80', 
    3: '100', 
    4: '120', 
  }
  return data[step]
}

module.exports = {
  COMMANDS,
  hexTransform,
  hexModel,
  echartLevel,
  ml_parseOneFrameArray,
  parseArray,
  filterWind
}